<template>
  <div>
    <van-nav-bar
      title="更新昵称"
      left-text="取消"
      right-text="保存"
      @click-left="$emit('on-cancel')"
      @click-right="onClickRight"
    />

    <van-field
      v-model="name"
      autosize
      type="textarea"
      maxlength="8"
      placeholder="请输入昵称"
      show-word-limit
    />
  </div>
</template>

<script>
import { setUserProfile } from '@/api/user.js'
export default {
  data() {
    return {
      name: this.value
    }
  },

  props: {
    value: {
      type: String,
      required: true
    }
  },

  created() {

  },

  methods: {
    async onClickRight() {
      if (this.name.trim() === '') return this.$toast('请输入用户名')
      try {
        await setUserProfile({
          name: this.name
        })
        this.$toast('修改成功')
        this.$emit('on-cancel')
        this.$emit('input', this.name)
      } catch (err) {
        console.dir(err)
        if (err.response && err.response.status === 409) {
          this.$toast('亲,名字已占用!')
          return
        }
        this.$toast('修改失败')
      }
    }
  }
}
</script>

<style scoped lang='less'>
</style>
